package com.example.service.impl;

import com.example.domain.po.OperationLog;
import com.example.mapper.OperationLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class LogService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private OperationLogMapper logMapper;

    /**
     * 从Redis获取日志并刷新到数据库
     * 此方法首先尝试从Redis中获取所有缓存的操作日志，然后清空Redis中的日志，
     * 接着将获取到的日志转换为实体对象列表，最后将这些实体对象批量插入数据库
     */
    public void refreshLogs() {
        List<Object> logs = new ArrayList<>();
        String key = "operation_logs";

        // 一次性获取所有日志并清空
        Long size = redisTemplate.opsForList().size(key);
        if (size != null && size > 0) {
            logs = redisTemplate.opsForList().range(key, 0, size - 1);
            redisTemplate.delete(key);
        }

        // 转换为实体列表
        List<OperationLog> entityList = convertToEntityList(logs);

        // 批量插入数据库
        if (!entityList.isEmpty()) {
            logMapper.batchInsert(entityList);
        }
    }

    /**
     * 将日志对象列表转换为实体列表
     * 此方法遍历每个日志对象，如果对象是Map类型，则将其转换为OperationLog实体，
     * 并添加到结果列表中
     *
     * @param logs 日志对象列表
     * @return 转换后的实体列表
     */
    private List<OperationLog> convertToEntityList(List<Object> logs) {
        List<OperationLog> result = new ArrayList<>();
        for (Object obj : logs) {
            if (obj instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> logMap = (Map<String, Object>) obj;
                OperationLog log = new OperationLog();
                log.setOperation((String) logMap.get("operation"));
                log.setMethod((String) logMap.get("method"));
                log.setParameters(logMap.get("parameters").toString());
                log.setResult(logMap.get("result").toString());
                log.setCreateTime(new Date((Long) logMap.get("timestamp")));
                result.add(log);
            }
        }
        return result;
    }
}

